package sharetime.web.view.flexjson;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.ui.Model;

public class JsonStringWriter {

	public String convertAndWrite(Model model, String[] excludeProperties) {
		return convertAndWrite(model.asMap(), excludeProperties);
	}

	@SuppressWarnings("unchecked")
	public String convertAndWrite(Map map, String[] excludeProperties) {

		JsonSerializer serializer = new JsonSerializer();

		return serializer.exclude("*.class").exclude(excludeProperties)
				.serialize(map);
	}

	@SuppressWarnings("unchecked")
	public String convertAndWrite(Model model, String[] excludeProperties,
			String[] includeProperties) {
		Map map = model.asMap();

		removeBindingResultFromModel(map);

		return convertAndWrite(map, excludeProperties, includeProperties);
	}

	@SuppressWarnings("unchecked")
	public String convertAndWrite(Map map, String[] excludeProperties,
			String[] includeProperties) {

		JsonSerializer serializer = new JsonSerializer();

		return serializer.exclude("*.class").exclude(excludeProperties)
				.include(includeProperties).serialize(map);
	}

	/**
	 * FIXME : 用其它方式片理掉bindingresult数据，使其不出现在json中
	 * 
	 * model contains BindingResult that should be removed
	 * 
	 * @param map
	 */
	@SuppressWarnings("unchecked")
	private void removeBindingResultFromModel(Map map) {
		for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) {
			Entry entry = (Entry) iter.next();
			String key = (String) entry.getKey();
			if (key.contains("org.springframework.validation.BindingResult")) {
				iter.remove();
				break;
			}
		}
	}
}
